package com.my.thread.test;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.my.cache.bean.CacheBean;
import com.my.cache.bean.jedis.JedisUtils;
import com.my.cache.utils.RedisTrafficVolumeBean;
import com.my.core.api.R;
import com.my.json.domain.JsonTest;
import com.my.log.config.annotation.ApiLog;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author timo 2020/12/4
 */
@RestController
@RequestMapping("testc")
@Slf4j
@RefreshScope
public class testcontroller {
//    @Autowired
//    HelloService helloService;
//    @Autowired
//    SheBaoServiceImpl sheBaoService2;
    @Value("${nacos.config-val:nacos.config-val未取到值}")
    private String aaa;

    @Autowired
    private RedisTrafficVolumeBean trafficVolumeUtils;

    @Autowired
//    @Qualifier("redisCacheBean")
    @Qualifier("ehcacheBean")
    protected CacheBean cacheBean;

    @Autowired
    private RedisTemplate redisTemplate;

    public static String base_url;
    @Value("${shebaoBaseUrl:cccc}")
    public void setBase_url(String base_url) {
        testcontroller.base_url = base_url;
    }
    //apilog添加了接口日志打印，但是没有保存
    @GetMapping("aaa")
    @ApiLog
    public String aaa(HttpServletRequest httpRequest) throws Exception {
        int aa = 1/0;
        return aaa;
    }

    //R 此处日志扫描所有返回值为R的控制器
    @RequestMapping(value="/heelo",produces = "application/json;charset=UTF-8")
    public R heelo(){
        System.out.println(base_url);

//        smsService.sendMsg("1","1","1","13551883869");
//        String s = helloService.sayHellSgl("科比");
//        return R.success(s);
//        return helloService.sayHellSgl("科比");
//        sheBaoService2.getCard("650102199401100046", "李玲霞", "13608021123");
        String a = "{\"idCard\":\"asa\",jybh:\"\",'userName':\"郑涛\"}";
//        JSONObject jsonObject = JSON.parseObject(a);
//        InputXml inputXml1 = JSONObject.parseObject(a, InputXml.class);
        JsonTest jsonTest = new JsonTest().setId("郑涛").setDate(new Date());
        JSON parse = JSONUtil.parse(jsonTest);
        String s5= JSONUtil.toJsonStr(jsonTest);
        String s = com.alibaba.fastjson.JSON.toJSONString(jsonTest);
        System.out.println(parse);

         trafficVolumeUtils.recordTrafficVolume();
        Long trafficVolume = trafficVolumeUtils.getTrafficVolume();
        System.out.println("trafficVolume:"+trafficVolume);

        JedisUtils.set("aaa",JedisUtils.get("aaa")+1,30000);
        System.out.println("JedisUtils---aaa:"+  JedisUtils.get("aaa"));

        if(cacheBean.get("test")==null){
            cacheBean.put("test",0,60);
        }
        cacheBean.put("test",(int)cacheBean.get("test")+1,60);
        System.out.println("cacheBean---test:"+  cacheBean.get("test"));

        redisTemplate.opsForValue().set("redisTemplate-test", 0, 30000, TimeUnit.SECONDS);
        System.out.println("redisTemplate---test:"+redisTemplate.opsForValue().get("redisTemplate-test"));

        return R.data(jsonTest);
    }

//    "650102199401100046", "李玲霞", "13608021123"

    /**
     * 回调
     *
     * @param httpRequest
     * @return
     * @throws Exception
     */
    @GetMapping("test4")
    public String test4(HttpServletRequest httpRequest) throws Exception {

        System.out.println(getDataFromRequest(httpRequest).toString());
        return "true";
    }

    @GetMapping("test5")
    public String test5() {
        String val = "UTrky5iYdVW8BuyPQPykuVevZ7XOhlhVfJiCu2+3mJ5JmqHLq/oAnindNnDlDPeHHC4ZOwzJ6YQX2cV6ROtzfvjcw/5pbZAgzsq1WJrcjMxSo7bBmhspFUf02pXmb/V0XpmFz79sshVoVZswdmqi9GSY+DoJn/RA7AKWHYO0ZvlSY8s6teyOyTPE3VP4LeIQsB/7nzunb4URs6W/0zHs0SpgedUzlG+35XaELxrtRzRM+pyqEilYqJTQxA7EyH7WIOE9yoXACmAeBo2yaHZV+vxplfUq11OfYuFsgHcJcZa3M3kdIjBmtej0LfccQjx0IeeWvQbB38cxE4w48D3wloqHTZCILPslUQDk3Aqto6zoaFxI8zoKhL559Jm0hCkGfjJcaUt561pnW/mvluiI1YlmAo0fvzS/NvkP/iSndJoH9MnHyr8i8rSFMp0c8E5gDGwB/xwTJLU6O3W0bXoN8w==";
        //社保查询符号不能通过数字签名认证 - 将加号替换为空格 对方再替换回来
        val = val.replace("+", " ");
//        return sheBaoService.callBackParse(val,
//                "650102199401100046", "李玲霞", "13608021123");
        return null;
    }

    /**
     * 读取request中传过来的字符串
     * 有些调用方不知道用什么方式调用，可能是【application/x-www-form-urlencoded】、【text/plain】、【application/json】
     * 该方法都能处理，但是如果是按【application/x-www-form-urlencoded】
     *
     * @param request
     * @return
     * @throws IOException
     */
    private Map<String, Object> getDataFromRequest(HttpServletRequest request) {
//        Gson gson = new Gson();
        String type = request.getContentType();
        System.out.println(type);
        Map<String, Object> receiveMap = new HashMap<String, Object>();
//        if("application/x-www-form-urlencoded".equals(type)){
        Enumeration<String> enu = request.getParameterNames();
        while (enu.hasMoreElements()) {
            String key = String.valueOf(enu.nextElement());
            String value = request.getParameter(key);
            receiveMap.put(key, value);
        }
//        }else{	//else是text/plain、application/json这两种情况
//            BufferedReader reader = null;
//            StringBuilder sb = new StringBuilder();
//            try{
//                reader = new BufferedReader(new InputStreamReader(request.getInputStream(), "utf-8"));
//                String line = null;
//                while ((line = reader.readLine()) != null){
//                    sb.append(line);
//                }
//            } catch (IOException e){
//                e.printStackTrace();
//            } finally {
//                try{
//                    if (null != reader){
//                        reader.close();
//                    }
//                } catch (IOException e){
//                    e.printStackTrace();
//                }
//            }
//            receiveMap = gson.fromJson(sb.toString(), new TypeToken<Map<String, String>>(){}.getType());//把JSON字符串转为对象
//        }
        return receiveMap;
    }
}
